package com.Java.train.pay.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.json.JSONUtil;
import com.Java.train.pay.config.AlipayConfig;
import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.lang.module.Configuration;
import java.nio.file.LinkOption;

@RestController
@RequestMapping
@AllArgsConstructor
public class PaymentController {
    private static final Logger LOG = LoggerFactory.getLogger(PaymentController.class);
//    @Resource
//    AlipayConfig alipayConfig;
    private final Config config;

    @GetMapping
    public String pay() throws Exception {
        // 注入config
        Factory.setOptions(config);

        AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace().preCreate("Apple iPhone11 1T", "22345678920", "5799.00");
        LOG.info("已生成二维码");
        String httpBody = response.getHttpBody();
        JSONObject jsonObject = JSONObject.parseObject(httpBody);
        String qrCode = jsonObject.getJSONObject("alipay_trade_precreate_response").get("qr_code").toString();

        QrCodeUtil.generate(qrCode, 500, 500, new File("D://nihao.jpg"));

        return httpBody;
    }

    @PostMapping("/notify")
    public String notify(HttpServletRequest request){
        LOG.info("收到支付宝反馈信息");
        String out_trade_no = request.getParameter("out_trade_no");
        LOG.info("流水号为：{}", out_trade_no);
        return out_trade_no;
    }
}
